import express from "express"
import { get, merge } from "lodash"

import { getUserBysessionToken } from "../db/users"


// 判断是否是本人
export const isOwner = async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  try {
    const { id } = req.params
    const currentUserId = get(req, 'identity._id') as string

    console.log('currentUserId', currentUserId)
    

    if (!id || !currentUserId) return res.sendStatus(400)
    
    if(id !== currentUserId.toString()) return res.sendStatus(403)

    return next()
  } catch (error) {
    console.log(error)
    return res.sendStatus(400)
  }
}

// 判断是否登录
export const isAuthenticated = async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  try {
    const sessionToken = req.cookies['token']

    if (!sessionToken) return res.sendStatus(403)

    const existingUser = await getUserBysessionToken(sessionToken)

    if (!existingUser) return res.sendStatus(403)

    merge(req, { identity: existingUser })

    return next()
  } catch (error) {
    console.log(error)
    return res.sendStatus(400)
  }
}
